package com.lzb.watermarkcamera;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzb.watermarkcamera.bean.CityBean;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class BaseApplication extends Application {
    public static Context context;
    public static List<CityBean> items;


    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        init();

    }

    private void init() {
        InputStream inputStream = null;

        try {
            inputStream = getResources().getAssets().open("citylist.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuilder json = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                json.append(line);
            }
            String jsonStr = json.toString(); // 这里就是你的JSON字符串
            Gson gson = new Gson();
            Type itemListType = new TypeToken<List<CityBean>>() {
            }.getType(); // 创建类型引用以解析列表类型。
            // 将JSON字符串转换为Item对象的列表。
            List<CityBean> lsitAll = gson.fromJson(jsonStr, itemListType);
            List<CityBean> cities = filterNonChinese(lsitAll, CityBean::getCityName);


            List<CityBean> validCities11 = new ArrayList<>();
            for (CityBean city : cities) {
                if (city != null && city.getCityName() != null && !city.getCityName().trim().isEmpty()) {
                    validCities11.add(city);
                }
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                items = distinctBy(validCities11, CityBean::getCityName);
            }
            Log.e("TAG", "init: ");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static <T> List<T> filterNonChinese(List<T> list, Function<T, String> fieldGetter) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return list.stream()
                    .filter(bean -> {
                        String value = fieldGetter.apply(bean);
                        return isChinese(value);
                    })
                    .collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 检查字符串是否仅包含中文
     *
     * @param str 待检查的字符串
     * @return 如果字符串为null、空或包含非中文则返回false
     */
    private static boolean isChinese(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        // 使用Unicode Script属性匹配所有中文汉字（包括扩展区）
        return str.matches("^\\p{Script=Han}+$");
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public static <T> List<T> distinctBy(List<T> list, Function<? super T, ?> keyExtractor) {
        return list.stream()
                .filter(distinctByKey(keyExtractor))
                .collect(Collectors.toList());
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

}